import Clipboard from 'clipboard'
import baseUrl from './base-url-config'
import * as actionTypes from '../actions/work-weixin'

export const invoke = (method = '', payload = {}) => {
  return new Promise((resolve, reject) => {
    console.log('查看企微调用')
    wx.invoke(method, payload, resp => {
      console.log('resp-------', resp)
      if (resp && resp.err_msg === `${method}:ok`) {
        resolve(resp)
      } else {
        reject(resp)
      }
    })
  })
}
/**
 * 注入企业配置
 * https://developer.work.weixin.qq.com/document/path/90514
 * @param config
 */
export const registerCorp = function (config) {
  return new Promise((resolve, reject) => {
    wx.config(config)
    wx.ready(resolve)
    wx.error(reject)
  })
}

/**
 * 注入应用配置
 * https://developer.work.weixin.qq.com/document/path/94313
 * @param config
 */
export const registerAgent = function (config) {
  return new Promise((resolve, reject) => {
    wx.agentConfig({
      ...config,
      success: resolve,
      fail: res => {
        reject(new Error(res))
      }
    })
  })
}
/**
 * 获取可用接口列表
 * https://developer.work.weixin.qq.com/document/path/94312
 * @param list
 */
export const getAvailableAPIs = function (list) {
  return new Promise((resolve, reject) => {
    wx.checkJsApi({
      jsApiList: list,
      success: resp => {
        // console.log('resp.errMsg', resp.errMsg)
        if (resp.errMsg === 'checkJsApi:ok') {
          const apis = resp.checkResult || {}
          resolve(Object.keys(apis).filter(key => apis[key]))
        } else {
          reject(resp)
        }
      },
      fail: reject
    })
  })
}

/**
 * 分享消息到当前会话
 * https://developer.work.weixin.qq.com/document/path/94349
 */
export const sendChatMessage = payload => {
  return invoke('sendChatMessage', payload)
}

// 转发到企业微信会话
// https://developer.work.weixin.qq.com/document/path/98225
export const shareAppMessage = payload => {
  return invoke('shareAppMessage', payload)
}

// 客户群发一天只能一次
// https://developer.work.weixin.qq.com/document/path/93555
export const shareToExternalContact = payload => {
  return invoke('shareToExternalContact', payload)
}

// 群发到客户群
// https://developer.work.weixin.qq.com/document/path/93556
export const shareToExternalChat = payload => {
  return invoke('shareToExternalChat', payload)
}

/**
 * 设置企业微信系统剪贴板的内容
 * https://developer.work.weixin.qq.com/document/path/98327
 * @param config
 */
export const setWXClipboardData = function (config) {
  return wx.setClipboardData(config)
}

/**
 * 设置第三方剪贴板的内容
 * @param config
 */
export const setClipboardData = function ({
  classname = '',
  success = () => { },
  fail = () => { }
}) {
  const clipboard = new Clipboard(classname)
  clipboard.on('success', success)
  clipboard.on('error', fail)
}
/**
 * 添加客户
 * https://developer.work.weixin.qq.com/document/path/93071
 */
export const addConsumer = function (callback = () => { }) {
  return invoke('navigateToAddCustomer', {}, callback)
}
/**
 * 打开会话
 * https://developer.work.weixin.qq.com/document/path/98145
 */
export const openEnterpriseChat = function (params) {
  return wx.openEnterpriseChat(params)
}
/**
 * 打开已有群聊并发送消息
 * https://developer.work.weixin.qq.com/document/path/98145
 */
export const openExistedChatWithMsg = function (params) {
  return wx.openExistedChatWithMsg(params)
}
/**
 * 自定义转发到微信
 * https://developer.work.weixin.qq.com/document/path/98226
 */
export const shareWechatMessage = function (params) {
  return invoke('shareWechatMessage', params)
}

/**
 * 自定义转发到朋友圈 --- 待测试
 * https://developer.work.weixin.qq.com/document/path/97583
 */
export const shareTimeline = function (params) {
  return invoke('shareTimeline', params)
}

/**
 * 自定义转发到客户朋友圈
 * https://developer.work.weixin.qq.com/document/path/94607
 */
export const shareToExternalMoments = function (params) {
  return invoke('shareToExternalMoments', params)
}

/**
 * 获取当前联系人 id
 * https://developer.work.weixin.qq.com/document/path/91799
 */
export const getCurExternalContact = function () {
  return invoke('getCurExternalContact').then(resp => resp.userId)
}
/**
 * 获取当前联系人群 id
 * https://developer.work.weixin.qq.com/document/path/92095
 */
export const getCurExternalChat = function () {
  return invoke('getCurExternalChat').then(resp => resp.chatId)
}


export default {
  /**
   * 根据 code 拿用户信息
   */
  getEmployeeWXInfoByCode: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-adapt/login/callback/external`,
    hasLoading: false
  },
  /**
   * 根据 deviceId 和 userTicket 拿当前员工的信息
   */
  /**
   * 根据 code 拿当前员工的信息
   */
  getEmployeeInfo: {
    method: 'post',
    url: `${baseUrl}/v2/system/qw/login`,
    hasLoading: false
  },

  /**
   * 根据当前领域值filedId 获取当前员工的权限信息以及当前领域下的部门基本信息
   */
  getUserPermissionForBusinessField: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-corp-manage/userInfo`,
    actionType: actionTypes.GET_USER_PERMISSION,
    hasLoading: false
  },
  /**
   * 获取企业应用的信息
   */
  getApplicationInfo: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-adapt/auth/get/configIds`,
    hasLoading: false
  },
  /**
   * 生成签名
   * @params {string}type enum {enterprise: 企业签名, application: 应用签名}
   * @params {string}url 调用JS接口页面的完整UR
   */
  createSignatureEnterprise: {
    method: 'post',
    url: `${baseUrl}/app/wecom/enterprise/ticket`,
    hasLoading: false
  },
  createSignatureApplication: {
    method: 'post',
    url: `${baseUrl}/app/wecom/application/ticket`,
    hasLoading: false
  },
  /**
   * @description 获取微信AppID
   */
  fetchAppId: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-adapt/wechat/getAppId`,
    hasLoading: true
  },
  /**
   * @description 获取微信用户信息
   */
  fetchWxUserInfo: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-adapt/wechat/getInfoByCode`,
    actionType: actionTypes.SET_WXUSER_INFO,
  },

  // 查询是否授权状态
  qryCurrentPageHasBeenAuthorized: {
    url: `${baseUrl}/fin-scrm-cloud-studio/mobile/pact/get`,
    method: 'get',
    hasLoading: true
  },
  /**
   * @description 渠道活码用户信息采集
   */
  collectUserInfo: {
    url: `${baseUrl}/fin-scrm-contact-way/wechat/collect`,
    method: 'post',
    actionType: actionTypes.SET_HEADLINE_INFO,
  },
  /**
   * @description 扫描活码（更新计数并返回渠道活码信息）
   */
  updateContactWayTrace: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-contact-way/wechat/trace`
  },

  // 微信验证签名
  verifySignature: {
    method: 'get',
    url: `${baseUrl}/fin-scrm-corp-manage/wechat/signature`,
  },

  /**
   * @description 获取管护企业微信的二维码
   */
  getQRManagerCode: {
    method: 'post',
    url: `${baseUrl}/fin-scrm-contact-way/wechat/empqrcode`
  },
  setFieldList({ commit }, data) {
    // 设置领域列表
    commit(actionTypes.SET_USER_FIELD_LIST, data)
  },

  setCurrentUserInfo({ commit }, data) {
    // 设置领域列表
    commit(actionTypes.SET_WXUSER_INFO, data)
  },

  setPermissionList({ commit }, data) {
    // 设置权限列表
    commit(actionTypes.SET_USER_PERMISSION_LIST, data)
  },
  setAdminRole ({ commit }, data) {
    // 设置当前领域管理员状态
    commit(actionTypes.SET_ADMIN_ROLE, data)
  },
  setHeadlineInfo ({ commit }, data) {
    // 设置渠道活码标题及宣传语
    commit(actionTypes.SET_HEADLINE_INFO, data)
  },

}

/**
 * 获取侧边栏当前打开环境
 * https://developer.work.weixin.qq.com/document/path/94315
 */
export const getEntryContext = function () {
  return invoke('getContext').then(resp => resp.entry)
}


